package cannot.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cannot.pojo.User;
import cannot.pojo.UserDetail;
import cannot.service.UserDetailService;
import cannot.service.UserRoleService;
import cannot.service.UserService;
import cannot.util.CookieUtil;

@Controller
public class LoginController {
	@Autowired
	UserService userService;
	@Autowired
	UserDetailService userDetailService;
	@Autowired
	UserRoleService userRoleService;
	/**
	 * 登录验证，ajax登录成功重定向到首页,否则跳转到登录页面
	 * @param model
	 * @param name
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(Model model, String name, String password,HttpServletResponse response) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(name, password);
		try {
			subject.login(token);
			Session session = subject.getSession();
			session.setAttribute("subject", subject);
			//设置有效时间
			SecurityUtils.getSubject().getSession().setTimeout(1800000);
			User u = userService.getByName(subject.getPrincipal().toString());
			UserDetail userDetail= userDetailService.getByForeginKey(u.getId());
			u.setUserDetail(userDetail);
			u.setSalt(null);
			u.setPassword(null);
			session.setAttribute("user", u);
			Cookie cookie = new Cookie("namecookie",name);
			cookie.setMaxAge(60*60*24*5);
			cookie.setPath("/");
			Cookie cookie1 = new Cookie("passwordcookie",password);
			cookie1.setMaxAge(60*60*24*5);
			cookie1.setPath("/");
			response.addCookie(cookie);
			response.addCookie(cookie1);
			
			return "redirect:fore_indexPage";

		} catch (AuthenticationException e) {
			model.addAttribute("error", "验证失败,请检查用户名或密码后重试");
			return "fore/foreLogin";
		}
	}
	/**
	 * 注册功能 注册成功后自动跳转到首页
	 * @param model
	 * @param name
	 * @param password
	 * @return
	 */
	@RequestMapping(value="register",method=RequestMethod.POST)
	public String register(Model model, String name, String password,HttpServletResponse response){
		String salt = new SecureRandomNumberGenerator().nextBytes().toString();
		int times = 2;
		String algorithmName = "md5";

		//判断用户名是否重复
		User u1 = userService.getByName(name);
		if(u1!=null){
			System.err.println("111");
			model.addAttribute("message", "该用户名已被占用！");
			return "fore/foreLogin";
		}else{
			String encodedPassword = new SimpleHash(algorithmName, password, salt, times).toString();
			//数据库中填入user数据
			User u = new User();
			u.setName(name);
			u.setPassword(encodedPassword);
			u.setSalt(salt);
			userService.add(u);
			//数据库中填入对应userDetail数据
			UserDetail userDetail = new UserDetail();
			userDetail.setNickname(name);
			userDetail.setForeginkey(u.getId());
			userDetailService.addUserDetail(userDetail);
			//为其赋予用户角色
			userRoleService.setRoles(u, new long[]{12});
			return login(model,name,password,response);
		}
	}
	
	/**
	 * 用户退出
	 * @return
	 */
	@RequestMapping("doLogout")
	public String doLogout(HttpServletRequest request,HttpServletResponse response){
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		session.removeAttribute("user");
		SecurityUtils.getSubject().logout();
		
		response.addCookie(CookieUtil.deleteCookie(request.getCookies(), "namecookie"));
		response.addCookie(CookieUtil.deleteCookie(request.getCookies(), "passwordcookie"));
		return "redirect:fore_indexPage";
	}
}
